package vip.george.p0006;

import java.util.ArrayList;
import java.util.List;

public class P6 {


    public String convert2(String s, int numRows) {
        if (numRows == 1) {
            return s;
        }
        List<StringBuilder> list = new ArrayList<>();
        for (int i = 0; i <numRows; i++) {
            list.add(new StringBuilder());
        }

        // 第i个字符所在的 行号（i从0开始，行号从1开始）
        int index = 1;
        //特别注意，最开始的箭头是向上的，因为初始字符处在最顶层，下一次箭头就要改为向下
        boolean down = false;
        for (char c : s.toCharArray()) {
            StringBuilder sb = list.get(index-1);
            sb.append(c);
            //计算下一个元素应该放置的行号
            if (index == numRows || index == 1) {
                down = !down;
            }
            // 根据箭头方向判断放置行号是加1还是减1
            index += down ? 1 : -1;
        }

        StringBuilder result = new StringBuilder();
        for (StringBuilder sb : list) {
            result.append(sb);
        }
        return result.toString();
    }


    public static void main(String[] args) {
        P6 p6 = new P6();
        System.out.println(p6.convert2("AB", 1));
        System.out.println(p6.convert2("PAYPALISHIRING", 3));
        System.out.println(p6.convert2("PAYPALISHIRING", 4));
    }

}
